package chances.wechat.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import chances.wechat.data.PageBean;
import chances.wechat.entity.UserHistory;
import chances.wechat.model.HistoryDelEvent;
import chances.wechat.model.HistoryEmptyEvent;
import chances.wechat.model.HistoryEvent;
import chances.wechat.resp.BaseResponse;
import chances.wechat.resp.ResultResponse;
import chances.wechat.resp.ResultSetResponse;
import chances.wechat.service.HistoryService;
import chances.wechat.service.StbDataService;
import chances.wechat.utils.RequestUtils;

@RestController
@RequestMapping(value = "/history")
public class HistoryController extends UserAbstractController {
    private static Logger logger = LoggerFactory.getLogger("contentData");

    @Autowired
    private HistoryService historyService;

    @Autowired
    StbDataService stbDataService;

    @RequestMapping(value = "/add")
    public BaseResponse addHistory(ModelMap model, HttpServletRequest request,
            HttpServletResponse response, @RequestParam String stbNo)
            throws IOException {
        BaseResponse result = new BaseResponse();

        UserHistory history = this.createUserHistory(request);
        // 参数检查
        if (StringUtils.isBlank(history.getUserId())
                || StringUtils.isBlank(history.getContentId())) {
            result.setStatus(VALID_PARAM);
            result.setMessage("lack param");
        } else {
            try {
                this.historyService.addUserHistory(history);

                HistoryEvent event = new HistoryEvent();
                event.setStbNo(stbNo);
                event.setUserHistory(history);
                this.applicationContext.publishEvent(event);
            } catch (Throwable ex) {
                result.setStatus(DB_ERROR);
                result.setMessage(ex.getMessage());
                logger.error("add user history error.", ex);
            }
        }
        return result;
    }

    /**
     * 批量删除历史
     * 
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/del")
    public BaseResponse delReqs(@RequestParam String codes,
            @RequestParam String userId, @RequestParam String stbNo) {
        ResultResponse<String> result = new ResultResponse<String>();
        try {
            if (StringUtils.isNotEmpty(codes)) {
                String[] codesArr = codes.split(",");
                this.historyService.dels(codesArr, userId);

                HistoryDelEvent event = new HistoryDelEvent();
                event.setStbNo(stbNo);
                event.setCodes(Arrays.asList(codesArr));
                this.applicationContext.publishEvent(event);
            }
            result.setStatus(SUCCESS);
        } catch (Throwable ex) {
            result.setStatus(DB_ERROR);
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 清空历史
     * 
     * @param model
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/clear")
    public BaseResponse clearHistory(@RequestParam String userId,
            @RequestParam String stbNo,
            @RequestParam(required = false, defaultValue = "") String category)
            throws IOException {
        BaseResponse result = new BaseResponse();
        // 参数检查
        if (StringUtils.isBlank(userId)) {
            result.setStatus(VALID_PARAM);
            result.setMessage("userId is empty");
        } else {
            try {
                this.historyService.clearUserHistories(userId, category);

                HistoryEmptyEvent event = new HistoryEmptyEvent();
                event.setStbNo(stbNo);
                this.applicationContext.publishEvent(event);
            } catch (Throwable ex) {
                logger.error("clear user history error.", ex);
                result.setStatus(DB_ERROR);
                result.setMessage(ex.getMessage());
            }
        }
        return result;
    }

    /**
     * 查询预约
     * 
     * @param model
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/list")
    public BaseResponse listHistory(HttpServletRequest request,
            @RequestParam String userId, @RequestParam String stbNo)
            throws IOException {
        ResultSetResponse<UserHistory> result = new ResultSetResponse<UserHistory>();

        try {
            PageBean page = this.getPageBean(request);
            if (stbDataService.sendToStb()) {
                return stbDataService.listHistory(stbNo, page.getCurrentPage(),
                        page.getRecordCount());
            }

            List<UserHistory> historyList = this.historyService
                    .listUserHistories(userId, null, null, null, null, page);
            result.setResultSet(historyList);
            result.setPageBean(page);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(DB_ERROR);
            result.setMessage(e.getMessage());
            return result;
        }
    }

    private UserHistory createUserHistory(HttpServletRequest request) {
        UserHistory history = new UserHistory();
        history.setContentId(
                RequestUtils.getParameter(request, "contentId", ""));
        history.setContentName(
                RequestUtils.getParameter(request, "contentName", ""));
        history.setContentPoster(
                RequestUtils.getParameter(request, "contentPoster", ""));
        history.setContentType(
                RequestUtils.getParameter(request, "contentType", ""));
        history.setElapsedTime(
                RequestUtils.getParameter(request, "elapsedTime", 0));
        history.setEpisodeIndex(
                RequestUtils.getParameter(request, "episodeIndex", 0));
        history.setPath(RequestUtils.getParameter(request, "path", ""));
        history.setProgramId(
                RequestUtils.getParameter(request, "programId", ""));
        history.setUserId(RequestUtils.getParameter(request, "userId", ""));
        history.setCategory(RequestUtils.getParameter(request, "category", ""));
        return history;
    }
}
